/*
 * @Author: 小豪
 * @Description:
 * @Date: 2024-04-10 17:26:58
 * @LastEditTime: 2024-05-22 18:24:31
 * @FilePath: \bsct\gohub\app\http\controllers\api\v1\auth\login_controller.go
 */
package auth

import (
	v1 "gohub/app/http/controllers/api/v1"
	"gohub/app/requests"
	"gohub/pkg/auth"
	"gohub/pkg/jwt"
	"gohub/pkg/response"
	"time"

	"github.com/gin-gonic/gin"
)

// LoginController 用户控制器
type LoginController struct {
	v1.BaseAPIController
}

// LoginByPhone 手机+密码登录
func (lc *LoginController) LoginByPhone(c *gin.Context) {
	// 1. 验证表单
	request := requests.LoginByPhoneRequest{}
	errs := requests.Validate(c, &request, requests.LoginByPhone)
	if len(errs) > 0 {
		// 失败，显示错误提示
		response.JSON(c, gin.H{
			"success":    false,
			"total_page": "",
			"status":     "100",
			"msg":        errs,
			"data":       map[string]string{},
			"time":       time.Now().Unix(),
		})
		return
	}
	// 2. 尝试登录
	user, err := auth.Attempt(request.Phone, request.Password)
	if err != nil {
		// 失败，显示错误提示
		response.JSON(c, gin.H{
			"success":    false,
			"total_page": "",
			"status":     "100",
			"msg":        "账号或密码有误！",
			"data":       map[string]string{},
			"time":       time.Now().Unix(),
		})
		return
	}
	// 登录成功
	token := jwt.NewJWT().IssueToken(user.GetStringID(), user.Name)
	response.JSON(c, gin.H{
		"success":    true,
		"total_page": "",
		"status":     "200",
		"msg":        "登录成功！",
		"data": map[string]string{
			"token": token,
		},
		"time": time.Now().Unix(),
	})

}

// RefreshToken 刷新 Access Token
func (lc *LoginController) RefreshToken(c *gin.Context) {

	token, err := jwt.NewJWT().RefreshToken(c)

	if err != nil {
		response.Errors(c, "令牌刷新失败")
	} else {
		response.JSON(c, gin.H{
			"success":    true,
			"total_page": "",
			"status":     "200",
			"msg":        "登录成功！",
			"data": map[string]string{
				"token": token,
			},
			"time": time.Now().Unix(),
		})
	}
}
